<script setup lang="ts">
import { reactive, ref } from "vue";
import type { RoleListType } from "@/types/RoleType.ts";
import { roleDefaultHome } from "@/services/roleApi.ts";
import { FormInstance, Message, ValidatedError } from "@arco-design/web-vue";
import type { FormRule } from "@/types/commonType.ts";

const emit = defineEmits<{
  (e: "list"): void;
}>();

const loading = ref<boolean>(false);

const visible = ref<boolean>(false);

const formRef = ref<FormInstance>();

const formModel = reactive({
  defaultHomePage: "",
  roleId: "",
  roleCode: "",
});

const rules: FormRule<"defaultHomePage"> = {
  defaultHomePage: {
    required: true,
    message: "请输入当前角色首页路由",
  },
};

const init = (row: RoleListType) => {
  formModel.roleId = row.id;
  formModel.defaultHomePage = row.defaultHome;
  formModel.roleCode = row.roleCode;
  visible.value = true;
  loading.value = false;
};

const handleOK = () => {
  formRef.value?.validate(
    (errors: undefined | Record<string, ValidatedError>) => {
      if (errors === undefined) {
        loading.value = true;
        const obj = JSON.parse(JSON.stringify(formModel));
        delete obj.roleCode;
        roleDefaultHome(obj)
          .then((res) => {
            if (res.code === 200) {
              emit("list");
              Message.success(res.data);
              visible.value = false;
            }
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  );
};

defineExpose({
  init,
});
</script>

<template>
  <a-modal
    title="默认首页"
    title-align="start"
    :visible="visible"
    @ok="handleOK"
    :ok-loading="loading"
    @cancel="visible = false"
  >
    <a-form
      auto-label-width
      ref="formRef"
      :rules="rules"
      :model="formModel"
    >
      <a-form-item label="角色编码">
        <a-input
          v-model="formModel.roleCode"
          readonly
        />
      </a-form-item>
      <a-form-item label="首页路由">
        <a-input
          v-model="formModel.defaultHomePage"
          placeholder="请输入当前角色首页路由"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="scss">
</style>